﻿using System;
using System.Data;
using System.Configuration;
using System.Collections;
using System.Web;
using System.Web.Security;
using System.Web.UI;
using System.Web.UI.WebControls;
using System.Web.UI.WebControls.WebParts;
using System.Web.UI.HtmlControls;
using System.Collections.Generic;
using LabMS.BLL;
using System.Text.RegularExpressions;

namespace LabMS.Web.PersonalProject
{
    public partial class AddPersonalProject : Base.BasePage
    {
        protected void Page_Load(object sender, EventArgs e)
        {
            strPageUserType.Add("student");
            if(!IsPostBack)
            {
                //绑定实验室
                LabDropdownlist();
            }

            ApplyTimeMin.Attributes.Add("onclick", "d.showMoreDay = false;d.show(this);");
            ApplyTimeMin.Attributes.Add("readOnly", "-1");
            ApplyTimeMax.Attributes.Add("onclick", "d.showMoreDay = false;d.show(this);");
            ApplyTimeMax.Attributes.Add("readOnly", "-1");
        }

        //绑定所属实验室
        protected void LabDropdownlist()
        {
            LabMS.BLL.Lab lab = new LabMS.BLL.Lab();
            List<LabMS.Model.Lab> ParLab = new List<LabMS.Model.Lab>();
            List<LabMS.Model.Lab> SonLab = new List<LabMS.Model.Lab>();
            List<LabMS.Model.Lab> LabTemp = new List<LabMS.Model.Lab>();

            ParLab = lab.GetModelList("Lab_ParentID is null");
            SonLab = lab.GetModelList("Lab_ParentID is not null");
            LabTemp = lab.GetModelList("Lab_ParentID is null");

            int count = ParLab.Count, count1 = SonLab.Count;
            for (int i = 0; i < count; i++)
            {
                int ID = ParLab[i].ID;
                int m = 0;
                for (int j = 0; j < count1; j++)
                {
                    LabMS.Model.Lab labModel = new LabMS.Model.Lab();
                    int ParentID = int.Parse(SonLab[j].Lab_ParentID.ToString());

                    if (ParentID == ID)
                    {
                        labModel.ID = SonLab[j].ID;
                        labModel.Lab_Name = "|-" + SonLab[j].Lab_Name;
                        LabTemp.Insert(i + m + 1, labModel);
                        m++;
                    }
                }
            }
            ddlApplyLab.DataSource = LabTemp;
            ddlApplyLab.DataBind();
            ListItem item = new ListItem("无", "0");
            ddlApplyLab.Items.Insert(0, item);
        }

        //保存
        protected void btnSave_Click(object sender, EventArgs e)
        {
            #region 验证
            if (string.IsNullOrEmpty(ProjectName.Text.Trim()))
            {
                LabMS.Common.JShelper.JSAlert(Page, "err", "项目名称不能为空!");
                return;
            }
            else if (ProjectName.Text.Trim().Length > 50)
            {
                LabMS.Common.JShelper.JSAlert(Page, "err", "项目名称长度不能超过50个字符或25个中文汉字!");
                return;
            }
            if (string.IsNullOrEmpty(PlanHours.Text.Trim()))
            {
                LabMS.Common.JShelper.JSAlert(Page, "err", "计划学时不能为空!");
                return;
            }
            int hour = 0;
            if (!int.TryParse(PlanHours.Text.Trim(), out hour))
            {
                LabMS.Common.JShelper.JSAlert(Page, "err", "计划学时必须是数字!");
                return;
            }
            if (ddlApplyLab.SelectedValue.ToString().Equals("0"))
            {
                LabMS.Common.JShelper.JSAlert(Page, "err", "申请实验室不能为空!");
                return;
            }

            if (string.IsNullOrEmpty(ApplyTimeMin.Text.Trim()) || string.IsNullOrEmpty(ApplyTimeMax.Text.Trim()))
            {
                LabMS.Common.JShelper.JSAlert(Page, "err", "申请时间不能为空!");
                return;
            }
            else
            {
                if (Convert.ToDateTime(ApplyTimeMin.Text.Trim()) > Convert.ToDateTime(ApplyTimeMax.Text.Trim()))
                {
                    LabMS.Common.JShelper.JSAlert(Page, "err", "申请开始时间大于结束时间!");
                    return;
                }
            }
            if (string.IsNullOrEmpty(tb_StudentIDs.Text.Trim()))
            {
                LabMS.Common.JShelper.JSAlert(Page, "err", "申请人不能为空!");
                return;
            }
            if (string.IsNullOrEmpty(Contactor.Text.Trim()))
            {
                LabMS.Common.JShelper.JSAlert(Page, "err", "联系人不能为空!");
                return;
            }

            
            if (string.IsNullOrEmpty(ContactPhone.Text.Trim()))
            {
                LabMS.Common.JShelper.JSAlert(Page, "err", "联系人的联系电话不能为空!");
                return;
            }

            string strRegex = @"^([a-zA-Z0-9_\-\.]+)@((\[[0-9]{1,3}\.[0-9]{1,3}\.[0-9]{1,3}\.)|(([a-zA-Z0-9\-]+\.)+))([a-zA-Z]{2,4}|[0-9]{1,3})(\]?)$";   
            Regex re = new Regex(strRegex);
            if (!string.IsNullOrEmpty(ContactEmail.Text.Trim()))
            {
                if (!re.IsMatch(ContactEmail.Text.Trim()))
                {
                    LabMS.Common.JShelper.JSAlert(Page, "err", "联系人的EMail地址格式不正确!");
                    return;
                }
            }
            if (!string.IsNullOrEmpty(TeacherEmail.Text.Trim()))
            {
                if (!re.IsMatch(TeacherEmail.Text.Trim()))
                {
                    LabMS.Common.JShelper.JSAlert(Page, "err", "指导老师的EMail地址格式不正确!");
                    return;
                }
            }

            int temp = 0;
            int Index = int.Parse(tb_EIndex.Value);           
            for (int i = 0; i < Index; i++)
            {
                if (!string.IsNullOrEmpty(Request.Form["name" + i + ""]))
                {
                    if (string.IsNullOrEmpty(Request.Form["num" + i + ""]))
                    {
                        LabMS.Common.JShelper.JSAlert(Page, "err", "所需仪器数量不能为空!");
                        return;
                    }
                    else
                    {
                        if (!int.TryParse(Request.Form["num" + i + ""], out temp))
                        {
                            LabMS.Common.JShelper.JSAlert(Page, "err", "所需仪器数量必须为数字!");
                            return;
                        }
                    }
                }
                else
                {
                    if (!string.IsNullOrEmpty(Request.Form["num" + i + ""]))
                    {
                        LabMS.Common.JShelper.JSAlert(Page, "err", "所需仪器名称不能为空!");
                        return;
                    }
                    else
                    {
                        if (!string.IsNullOrEmpty(Request.Form["intro" + i + ""]))
                        {
                            LabMS.Common.JShelper.JSAlert(Page, "err", "所需仪器名称不能为空!");
                            return;
                        }
                    }
                }
            }
            Index = int.Parse(tb_ConsumpIndex.Value);
            for (int i = 0; i < Index; i++)
            {
                if (!string.IsNullOrEmpty(Request.Form["consumpname" + i + ""]))
                {
                    if (string.IsNullOrEmpty(Request.Form["consumpnum" + i + ""]))
                    {
                        LabMS.Common.JShelper.JSAlert(Page, "err", "所需低耗品数量不能为空!");
                        return;
                    }
                    else
                    {
                        if (!int.TryParse(Request.Form["consumpnum" + i + ""], out temp))
                        {
                            LabMS.Common.JShelper.JSAlert(Page, "err", "所需低耗品数量必须为数字!");
                            return;
                        }
                    }
                }
                else
                {
                    if (!string.IsNullOrEmpty(Request.Form["consumpnum" + i + ""]))
                    {
                        LabMS.Common.JShelper.JSAlert(Page, "err", "所需低耗品名称不能为空!");
                        return;
                    }
                    else
                    {
                        if (!string.IsNullOrEmpty(Request.Form["consumpintro" + i + ""]))
                        {
                            LabMS.Common.JShelper.JSAlert(Page, "err", "所需低耗品名称不能为空!");
                            return;
                        }
                    }
                }
            }
            #endregion
            LabMS.BLL.PersonalProject projectinfo = new LabMS.BLL.PersonalProject();
            LabMS.Model.PersonalProject project = new LabMS.Model.PersonalProject();

            project.ProjectName = ProjectName.Text.Trim();
            project.PlanHours = int.Parse(PlanHours.Text.Trim());
            project.AppcationLabID = int.Parse(ddlApplyLab.SelectedValue.Trim());

            DateTime tempTime = new DateTime();
            if (DateTime.TryParse(ApplyTimeMin.Text.Trim(), out tempTime))
            {
                project.ApplicationStartTime = tempTime;
            }
            if (DateTime.TryParse(ApplyTimeMax.Text.Trim(), out tempTime))
            {
                project.ApplicationEndTime = tempTime;
            }

            LabMS.Model.SysSetting msys = new LabMS.Model.SysSetting();
            ExtendBLL.SysSetting extendsys = new ExtendBLL.SysSetting();
            msys = extendsys.GetCurrentSetting();
            project.SYear = msys.CurrentYear;
            project.Semester = msys.CurrentSemester;

            project.Contactor = Contactor.Text.Trim();
            project.ContactorClass = ContactorClass.Text.Trim();
            project.ContactorEmail = ContactEmail.Text;
            project.ContactorPhone = ContactPhone.Text.Trim();

            project.Teacher = Teacher.Text.Trim();
            project.TeacherTitle = TeacherTitle.Text.Trim();
            project.TeacherEmail = TeacherEmail.Text;
            project.TeacherPhone = TeacherPhone.Text.Trim();

            project.ApplicationReason = ApplyReason.Text.Trim();
            project.ProjectStatus = "1";//状态为未申请(status=1)
            string strAlertContent = "保存成功!";
            string strAlertFailContent = "保存失败!";
            if (((Button)sender).ID == "btnApply")
            {
                strAlertContent = "申请成功!";
                strAlertFailContent = "申请失败!";
                project.ProjectStatus = "2";
            }
            //添加申请人
            string[] array = tb_StudentIDs.Text.Split(',');
            List<string> lsIDs = new List<string>();

            lsIDs.Add(array[0]);

            foreach (string item in array)
            {
                int Count = 0;
                foreach (string Pr in lsIDs)
                {
                    if (item != Pr)
                    {
                        Count++;
                    }
                }
                if (Count == lsIDs.Count)
                {
                    lsIDs.Add(item);
                }
            }
            
            try
            {
                int ProjectID = projectinfo.Add(project);
                LabMS.BLL.PersonalProjApp applicantinfo = new LabMS.BLL.PersonalProjApp();
                LabMS.Model.PersonalProjApp applicant = new LabMS.Model.PersonalProjApp();

                if (!array[0].Equals(""))
                {
                    for (int i = 0; i < lsIDs.Count; i++)
                    {
                        applicant.ApplicantID = int.Parse(lsIDs[i]);
                        applicant.PersonalProjID = ProjectID;
                        applicantinfo.Add(applicant);
                    }
                }

                //添加仪器
                int EquipIndex = int.Parse(tb_EIndex.Value);
                LabMS.BLL.PersonalProjConsume consumeinfo = new PersonalProjConsume();
                LabMS.Model.PersonalProjConsume consume = new LabMS.Model.PersonalProjConsume();
                for (int i = 0; i < EquipIndex; i++)
                {
                    string EquipName = "";
                    int EquipNum = 0;
                    string Introduction = "";
                    try
                    {
                        if ((!string.IsNullOrEmpty(Request.Form["name" + i + ""])) && (!string.IsNullOrEmpty(Request.Form["num" + i + ""])))
                        {
                            EquipName = Request.Form["name" + i + ""];
                            EquipNum = int.Parse(Request.Form["num" + i + ""]);
                            Introduction = Request.Form["intro" + i + ""];

                            consume.EquipName = EquipName;
                            consume.EquipNum = EquipNum;
                            consume.EquipType = 1;
                            consume.Introduction = Introduction;
                            consume.PersonalProjID = ProjectID;

                            consumeinfo.Add(consume);
                        }
                    }
                    catch { }
                }

                //添加低耗品
                int ConsumpIndex = int.Parse(tb_ConsumpIndex.Value);
                for (int i = 0; i < ConsumpIndex; i++)
                {
                    string ConsumpName = "";
                    int ConsumpNum = 0;
                    string ConsumpIntro = "";
                    try
                    {
                        if ((!string.IsNullOrEmpty(Request.Form["consumpname" + i + ""])) && (!string.IsNullOrEmpty(Request.Form["consumpnum" + i + ""])))
                        {
                            ConsumpName = Request.Form["consumpname" + i + ""];
                            ConsumpNum = int.Parse(Request.Form["consumpnum" + i + ""]);
                            ConsumpIntro = Request.Form["consumpintro" + i + ""];

                            consume.EquipName = ConsumpName;
                            consume.EquipNum = ConsumpNum;
                            consume.EquipType = 2;
                            consume.Introduction = ConsumpIntro;
                            consume.PersonalProjID = ProjectID;

                            consumeinfo.Add(consume);
                        }
                    }
                    catch { }
                }
                LabMS.Common.JShelper.JSAlertAndRedirect(Page, "AddSuccess", strAlertContent, "ListPersonalProject.aspx");
            }
            catch
            {
                LabMS.Common.JShelper.JSAlert(Page, "AddFailed", strAlertFailContent);
            }            
        }

        //protected void Gv_DataBinds()
        //{
        //    List<ExtendModule.StudentAndOther> studentlist = new List<ExtendModule.StudentAndOther>();
        //    ExtendBLL.PersonalProject project = new ExtendBLL.PersonalProject();

        //    string strWhere = CombineStr();
        //    if (!string.IsNullOrEmpty(strWhere))
        //    {
        //        studentlist = project.GetStudentInfoListByID(strWhere);
        //        gvAddApplicant.DataSource = studentlist;
        //        gvAddApplicant.DataBind();
        //    }
        //    else
        //    {
        //        gvAddApplicant.DataSource = studentlist;
        //        gvAddApplicant.DataBind();
        //    }
        //} 

        //protected string CombineStr()
        //{
        //    string strWhere = "";
        //    string[] text = tb_StudentIDs.Text.Split(',');
        //    if (text.Length != 0)
        //    {
        //        foreach (string Item in text)
        //        {
        //            if (!string.IsNullOrEmpty(strWhere))
        //            {
        //                strWhere += " or ";
        //                strWhere += " s.ID ='" + Item + "' ";
        //            }
        //            else
        //            {
        //                strWhere = " s.ID='" + Item + "' ";
        //            }
        //        }
        //    }
        //    return strWhere;
        //}

        ////删除
        //protected void Delete_Click(object sender, EventArgs e)
        //{
        //    string[] Main = tb_StudentIDs.Text.Split(',');
        //    LinkButton lb = (LinkButton)sender;
        //    string ID = lb.CommandArgument;
        //    List<string> ls = new List<string>();
        //    foreach (string item in Main)
        //    {
        //        if (item != ID)
        //        {
        //            ls.Add(item);
        //        }
        //    }
        //    tb_StudentIDs.Text = "";
        //    foreach (string Item in ls)
        //    {
        //        if (!string.IsNullOrEmpty(tb_StudentIDs.Text))
        //        {
        //            tb_StudentIDs.Text += ",";
        //            tb_StudentIDs.Text += Item; ;
        //        }
        //        else
        //        {
        //            tb_StudentIDs.Text += Item;
        //        }
        //    }
        //    Gv_DataBinds();
        //    tb_Tag.Text = "0";
        //}
    }
}
